<template>
  <view class="container">
    <FilterNavbar>
      <template #center>
        <view class="navbar-title"> {{ pageTitle }} </view>
      </template>
    </FilterNavbar>
    <view class="content">
      <ve-form ref="formRef" :model="form" :rules="rules">
        <!-- 工单、业务单信息 -->
        <formContent :routeQuery="routeQuery" @getRefCarInfoList="getRefCarInfoList" />
        <!-- 费用明细 -->
        <ve-card v-for="(item, index) in form.feeList" :key="index" :title="`费用明细 - ${index + 1}`" type="none">
          <FeeItem :listLength="form.feeList.length" :itemIndex="index" :info="item" @delete="handleDelete" @changeFee="changeFee" />
        </ve-card>
        <view
          v-if="form.feeList.length < 10"
          class="ve-form-item-btn"
          :class="[form.feeList.length ? 've-form-item-btn-have-data' : '']"
          @click="addFee"
        >
          <ve-icon name="plus" size="30"></ve-icon>
          <span class="ve-form-item-btn-text">添加</span>
        </view>

        <ve-card type="none">
          <ve-form-item label="申请备注" labelPosition="top" :borderBottom="false">
            <ve-input type="textarea" v-model="form.remark" placeholder="请输入备注" :maxlength="200" />
          </ve-form-item>
        </ve-card>
        <ve-card type="none">
          <ve-form-item label="收款方信息">
            <view style="text-align: right">
              <view>{{ form.collectStaffName || '-' }} - {{ form.collectStaffPhone }}</view>
              <view style="text-align: right">{{ form.collectStaffOrgName || '-' }} </view>
            </view>
          </ve-form-item>
          <ve-form-item label="收款账号" :borderBottom="false" prop="collectCard" required>
            <view class="bank-select" @click="toBankInfo">
              <view v-if="form.collectBackId" style="text-align: right">
                <view>{{ form.collectInExpWayName }}</view>
                <view>{{ form.collectCard }}</view>
                <view>{{ form.collectBackName }}</view>
                <!-- <view v-if="form.collectBackProvinceName || form.collectBackCityName">
                  {{ form.collectBackProvinceName || '-' }} | {{ form.collectBackCityName || '-' }}
                </view> -->
              </view>
              <view v-else>
                <text style="font-size: 29rpx; color: #9ea5bb">请选择 </text>
              </view>
              <ve-icon style="margin-left: 10rpx" name="arrow_right_0" size="32" />
            </view>
          </ve-form-item>
        </ve-card>
        <!-- 审批人模块 -->
        <form-approval-content :pageTitle="pageTitle" v-if="form.ifOpenCheck" />
      </ve-form>
    </view>

    <view style="height: 300rpx">
      <ve-bottom-box>
        <view class="fee-footer">
          <view class="fee-summary-sum">
            <view class="fee-summary-amount">
              <text>费用合计：</text>
              <text class="amount">{{ form.amount }}</text>
              <text class="unit">元</text>
            </view>
            <view class="fee-num"> 共 {{ form.feeList.length }} 笔 </view>
          </view>
          <view class="line"></view>
          <ve-button type="primary" @click="onConfirm" style="width: 100%" :loading="okLoading">确认</ve-button>
        </view>
      </ve-bottom-box>
    </view>
  </view>
</template>
<script setup>
  import { ref, provide, computed, nextTick, watch } from 'vue'
  import FilterNavbar from '@/components/FilterNavbar'
  import formContent from '../components/formContent.vue'
  import formApprovalContent from '../components/form-approval-content.vue'
  import FeeItem from '../components/feeItem.vue'
  import { staffDetail } from '@/api/cost/index'
  import {
    getApprovalSetings,
    getStaffList,
    editCostApi,
    getCostDetailApi,
    getNewCostDetailApi,
    getShortCarRecord,
    getLongCarRecord,
    getCheckHistoryApi,
  } from '@/api/cost/index'
  import { detailAPI } from '@/api/order/workOrder'
  import { findUserInfo } from '@/api/common/index'
  import dayjs from 'dayjs'
  import { onLoad, onShow } from '@dcloudio/uni-app'
  import useFormFold from '@/hooks/useFormFold'
  const { foldValidate } = useFormFold([])

  const pageTitle = ref('新增报销单')
  const form = ref({
    refCostType: 1,
    workInfo: '-',
    memberInfo: '-',
    feeOrgName: '-',
    amount: 0,
    ifOpenCheck: 0,
    feeList: [
      {
        amount: null,
        item: null,
        itemName: null,
        occurTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        fileIdList: [],
        carId: '',
        carModel: '-',
      },
    ],
    feeAmount: 0,
  })

  // 关联工单，关联业务单 费用明细车牌号，车型数据
  const refCarInfoList = ref([])

  provide('form', form)
  provide('refCarInfoList', refCarInfoList)

  const routeQuery = ref()
  const formRef = ref()
  const rules = computed(() => {
    const _rules = {}
    form.value.feeList.forEach((item, index) => {
      _rules[`feeList.${index}.amount`] = {
        required: true,
        message: '请选择',
      }
      _rules[`feeList.${index}.item`] = {
        required: true,
        message: '请选择',
      }
      _rules[`feeList.${index}.occurTime`] = {
        required: true,
        message: '请选择',
      }
      _rules[`feeList.${index}.fileIdList`] = {
        required: true,
        message: '请上传',
      }
    })
    _rules['refCostType'] = {
      required: true,
      message: '请选择',
    }
    if (form.value.refCostType == 1) {
      _rules['workType'] = {
        required: true,
        message: '请选择',
      }
      _rules['workId'] = {
        required: true,
        message: '请选择',
      }
    }
    if (form.value.refCostType == 2) {
      _rules['businessType'] = {
        required: true,
        message: '请选择',
      }
      _rules['businessId'] = {
        required: true,
        message: '请选择',
      }
    }

    _rules['feeOrgId'] = {
      required: true,
      message: '请选择',
    }
    _rules['collectCard'] = {
      required: true,
      message: '请选择',
    }
    return _rules
  })

  // 获取业务单和工单车辆信息列表
  const getRefCarInfoList = () => {
    let businessId = form.value.businessId
    let workId = form.value.workId
    if (businessId && form.value.refCostType == 2) {
      getBusinessCarList(businessId)
    }
    if (workId) {
      getWorkCarList(workId)
    }
  }
  // 获取业务单车辆数据
  const getBusinessCarList = (id) => {
    let fetch = form.value.businessType == 1 ? getShortCarRecord : getLongCarRecord
    fetch({ id: id }).then((res) => {
      refCarInfoList.value = res.result.map((item) => {
        return {
          value: item.carId,
          label: item.licenseNo,
          carId: item.carId,
          licenseNo: item.licenseNo,
          modelId: item.modelId,
          modelName: item.modelName,
        }
      })
      if (res.result?.length == 1) {
        // 费用信息回填车牌号和车型名称
        form.value.feeList.forEach((i) => ((i.carId = res.result[0].carId), (i.carModel = res.result[0].carModelName)))
      }
    })
  }
  // 获取工单车辆数据
  const getWorkCarList = (id) => {
    detailAPI({ id: id }).then((res) => {
      refCarInfoList.value = []
      let result = res.result
      // 交车和还车工单时只会回填一条数据
      if (result.workType == 1 || result.workType == 2) {
        if (result.carLicenseNo) {
          refCarInfoList.value = [
            {
              value: result.carId,
              label: result.carLicenseNo,
              carId: result.carId,
              modelId: result.carModelId,
              modelName: result.carModelName,
              licenseNo: result.carLicenseNo,
            },
          ]
          // 费用信息回填车牌号和车型名称
          form.value.feeList.forEach((i) => ((i.carId = result.carId), (i.carModel = result.carModelName)))
        }
      } else {
        // 换车工单时会回填多条数据
        if (result.carLicenseNo) {
          refCarInfoList.value.push({
            value: result.carId,
            label: result.carLicenseNo,
            carId: result.carId,
            modelId: result.carModelId,
            modelName: result.carModelName,
            licenseNo: result.carLicenseNo,
          })
        }
        if (result.replacedCarLicenseNo) {
          refCarInfoList.value.push({
            value: result.replacedCarId,
            label: result.replacedCarLicenseNo,
            carId: result.replacedCarId,
            modelId: result.replacedCarModelId,
            modelName: result.replacedCarModelName,
            licenseNo: result.replacedCarLicenseNo,
          })
        }
      }
    })
  }
  // 新增费用明细
  const addFee = () => {
    form.value.feeList.push({
      item: null,
      amount: '',
      occurTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      fileIdList: [],
      carModel: '-',
    })
    getRefCarInfoList()
  }
  // 删除费用信息
  const handleDelete = (e) => {
    uni.showModal({
      title: '提示',
      content: `是否要删除报销明细${e + 1}？`,
      success: (res) => {
        if (res.confirm) {
          form.value.feeList.splice(e, 1)
          uni.showToast({
            title: '已删除',
            icon: 'none',
          })
          changeFee()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }
  // 更改费用
  const changeFee = () => {
    let sum = 0
    form.value.feeList.forEach((item) => {
      sum += item.amount || 0
    })

    form.value.amount = sum
  }

  // 获取审批人数据
  const staffData = ref([])
  const getStaffData = () => {
    let params = {
      pageNumber: 1,
      pageSize: 200,
      status: 1,
    }
    getStaffList(params).then((res) => {
      if (res.code == 200) {
        staffData.value = res.result.data
      }
    })
  }
  // 最新配置审批人数据
  const newFlowList = ref([])
  // 最新审批开关
  const isNewOpenCheck = ref()
  // 获取员工列表
  const getApprovalSet = () => {
    getApprovalSetings({
      type: 1,
    }).then((res) => {
      if (res.code == 200) {
        // 默认无填充1个空值
        const flowList = res.result.flowList
        if (!flowList || flowList.length == 0) {
          res.result.flowList = [{ id: 0, post: undefined }]
        }
        if (!form.value.id) {
          form.value.checkFlowList = flowList.map((item) => {
            return {
              post: item.post,
              postName: item.postName,
              staffName: '',
            }
          })
        }
        newFlowList.value = flowList.map((item) => {
          return {
            post: item.post,
            postName: item.postName,
          }
        })
        isNewOpenCheck.value = res.result.ifOpen
        form.value.ifOpenCheck = isNewOpenCheck.value
        if (!form.value.id) {
          getCheckHistory()
        }
      }
    })
  }
  // 查询审批流程历史
  const getCheckHistory = () => {
    getCheckHistoryApi().then((res) => {
      form.value.checkFlowList = res.result.length > 0 ? res.result : newFlowList.value
    })
  }
  // 获取员工登录信息
  const getUserInfoApi = () => {
    findUserInfo({}).then((res) => {
      if (res.code == 200) {
        const data = res.result
        staffData.value = data
        form.value.collectId = data.employeeId
        if (!form.value.id) {
          form.value.loginUserId = data.employeeId
        }
        form.value.collectStaffName = data.realname
        form.value.collectStaffPhone = data.phone
        form.value.collectStaffOrgName = data.organizationName
        form.value.payeeInfo = `${data.realname} - ${data.phone} - ${data.organizationName}`
      }
    })
  }
  // 选择收款账户
  const toBankInfo = () => {
    uni.navigateTo({
      url: `/pages/operate-cost/bankInfo/list?id=${form.value.loginUserId}&collectBackId=${form.value.collectBackId}&orderType=staffOrder`,
    })
  }

  const okLoading = ref(false)
  const onConfirm = () => {
    okLoading.value = true
    formRef.value.validate((valid, errors) => {
      if (valid) {
        form.value.costType = 1
        form.value.collectType = 1
        if (routeQuery.value.type == 'againType') {
          form.value.id = ''
          form.value.ifReApply = 1
        }
        // 新增强制更新
        const isCreate = !form.value.id
        editCostApi({ ...form.value })
          .then((res) => {
            if (routeQuery.value?.routeType == 'reason') {
              uni.navigateBack({ delta: 2 })
            } else {
              uni.navigateBack()
            }

            uni.$emit('refreshData', isCreate)
            uni.showToast({
              title: res.message,
              icon: 'none',
            })
            okLoading.value = false
          })
          .catch((error) => {
            uni.showToast({
              title: error.data.message,
              icon: 'none',
            })
            okLoading.value = false
          })
      } else {
        okLoading.value = false
        // 页面滚动到错误位置
        foldValidate(errors)
      }
    })
  }
  const backInfoList = ref([])
  // 获取详情
  const getDetailInfo = (id) => {
    form.value.id = id
    let fetch = routeQuery.value.type == 'againType' ? getNewCostDetailApi : getCostDetailApi
    fetch({ id: id }).then((res) => {
      form.value = res.result
      form.value.feeList.map((i) => {
        i.occurTime = dayjs(i.occurTime).format('YYYY-MM-DD HH:mm:ss')
      })
      form.value.workInfo = form.value.businessTypeName + form.value.businessCode || '-'
      form.value.memberInfo = form.value.memberName + form.value.memberPhone || '-'
      form.value.payeeInfo = `${form.value.collectStaffName} - ${form.value.collectStaffPhone} - ${form.value.collectStaffOrgName}`
      // 重新申请，比较详情和配置审批流岗位及层级，相同取详情里面的，不同取配置最新的
      let detailFlowList = res.result.checkFlowList.map((item) => {
        return {
          post: item.post,
          postName: item.postName,
        }
      })
      if (routeQuery.value.type == 'againType') {
        form.value.ifOpenCheck = isNewOpenCheck.value
        if (JSON.stringify(detailFlowList) == JSON.stringify(newFlowList.value) && isNewOpenCheck.value) {
          form.value.checkFlowList = res.result.checkFlowList
        } else {
          form.value.checkFlowList = newFlowList.value
        }
      }
      // 修改时，工单号列表参数取自申请人id
      form.value.loginUserId = form.value.applyStaffId

      staffDetail({ id: form.value.applyStaffId }).then((val) => {
        const result = val.result
        backInfoList.value = result.backInfoList || []
        form.value.collectBackId = backInfoList.value?.find((i) => i.id == form.value.collectBackId) ? form.value.collectBackId : ''
      })
      // 获取费用车辆信息
      getRefCarInfoList()
    })
  }
  onLoad((option) => {
    getApprovalSet()
    getUserInfoApi()
    getStaffData()
    routeQuery.value = option
    if (routeQuery.value.id) {
      getDetailInfo(routeQuery.value.id)
      pageTitle.value = routeQuery.value.type == 'againType' ? '重新申请报销单' : '修改报销单'
    }
    if (routeQuery.value.costParams) {
      let costData = JSON.parse(routeQuery.value.costParams)
      form.value.workType = costData.workType
      form.value.workTypeName = costData.workTypeName
      form.value.workId = costData.id
      form.value.workCode = costData.workCode
      form.value.workInfo = (costData.refType == 1 ? '短租' : '长租') + costData.refCode || '-'
      form.value.memberInfo = costData.memberName + costData.memberPhone || '-'
      form.value.businessType = costData.refType
      form.value.businessId = costData.refId
      form.value.businessCode = costData.refCode
      form.value.feeOrgId = costData.siteId
      form.value.feeSiteId = costData.siteId
      form.value.feeOrgName = costData.siteName
    }
    if (routeQuery.value.orderParams) {
      let orderData = JSON.parse(routeQuery.value.orderParams)
      form.value.refCostType = orderData.refCostType
      form.value.businessType = orderData.businessType
      form.value.businessTypeName = orderData.businessType == 1 ? '短租' : '长租'
      form.value.businessId = orderData.businessId
      form.value.businessCode = orderData.businessCode
      form.value.memberInfo = orderData.memberName + orderData.memberPhone || '-'
      form.value.feeOrgId = orderData.feeOrgId
      form.value.feeSiteId = orderData.feeOrgId
      form.value.feeOrgName = orderData.feeOrgName
    }
    // 获取费用车辆信息
    getRefCarInfoList()
    if (routeQuery.value?.page == 'operateCost') form.value.refCostType = 2
  })

  onShow(() => {
    let checkedBankInfoStorage = uni.getStorageSync('checkedBankInfo')
    console.log(checkedBankInfoStorage, 'checkedBankInfoStorage')
    if (checkedBankInfoStorage) {
      form.value.collectBackId = checkedBankInfoStorage.id
      form.value.collectInExpWay = checkedBankInfoStorage.inExpWay
      form.value.collectInExpWayName = checkedBankInfoStorage.inExpWayName
      form.value.collectCard = checkedBankInfoStorage.bankCardNumber
      form.value.collectBackName = checkedBankInfoStorage.bank
      // form.value.collectBackProvinceCode = checkedBankInfoStorage.provinceCode
      // form.value.collectBackCityCode = checkedBankInfoStorage.cityCode
      // form.value.collectBackProvinceName = checkedBankInfoStorage.provinceName
      // form.value.collectBackCityName = checkedBankInfoStorage.cityName
    }
    uni.removeStorageSync('checkedBankInfo')
  })
</script>
<style lang="scss" scoped>
  page {
    background: #f7f8fa;
  }
  .content {
    height: auto;
    padding: 24rpx;
    background: #f7f8fa;
  }
  :deep(.ve-picker-box-body) {
    height: 25vh !important;
  }
  :deep(.ve-textarea) {
    background: #eff0f2;
  }
  .bank-select {
    display: flex;
    align-items: center;
  }
  .ve-form-item-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 88rpx;
    background: #f3f7ff;
    border-radius: 4rpx 4rpx 4rpx 4rpx;
    border: 2rpx solid #3072f6;
    .ve-form-item-btn-text {
      font-size: 30rpx;
      font-weight: 400;
      color: #3072f6;
      margin-left: 18rpx;
    }
  }
  .ve-form-item-btn-have-data {
    margin: 32rpx 0;
  }

  .fee-footer {
    width: 100%;
    background: #ffffff;
    display: flex;
    flex-direction: column;
    .fee-summary-sum {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12rpx 0 32rpx;

      .fee-summary-amount {
        display: flex;
        align-items: center;
        font-size: 32rpx;
        color: #1e1e1e;
        .amount {
          font-size: 48rpx;
          font-weight: 600;
          line-height: 1;
          color: #fe615a;
        }
        .unit {
          color: #fe615aff;
          font-size: 24rpx;
          vertical-align: bottom;
          margin-left: 8rpx;
        }
      }
    }
    .line {
      width: 100%;
      background: rgba(216, 216, 216, 0.3);
      height: 1px;
      margin-bottom: 32rpx;
    }
    .btn {
      padding: 32rpx 24rpx;
    }
  }
</style>
